<template>
  <el-form
    ref="form"
    :inline="inline"
    :model="formData"
    label-position="right"
    :label-width="labelWidth"
  >
    <el-form-item
      v-for="item in formItems"
      :key="item.id"
      :label="item.label"
      :prop="item.prop"
      v-bind="item.itemAttrs"
    >
      <component
        :is="item.com"
        v-bind="item.attrs"
        v-model="formData[item.prop]"
        v-on="getEvents(item.events)"
      />
    </el-form-item>
  </el-form>
</template>

<script setup>
import {computed, ref, watch,useAttrs }from 'vue'
const emits =defineEmits(['update:modelValue'])
const props = defineProps({
    formItems:{
        type:Array,
        default:()=>[]
    },
    inline:{
        type:Boolean,
        default:false
    },
    labelWidth:{
        type:[Number,String],
        default:''
    },
    modelValue:{
        type:Object,
        default:null
    }
      
})


const attrs =useAttrs()
const updateHandle = attrs['onUpdate:normalFormData']


const form =ref(null)
const formData =computed(()=> props.modelValue||attrs.normalFormData||{})


watch(()=>formData.value,(val)=>{
    if(props.modelValue){
        emits('update:modelValue',val)
    }else{
        updateHandle&&updateHandle(val)
    }
},{deep:true})




const getEvents = (events)=>{
    if(!events){
        return {}
    }
    const es ={}
    Object.keys(events).forEach(event=>{
        es[event]=(...args)=>{
            return events[event](args,formData.value)
        }
    })
    return es
}


defineExpose({
    formData,
    form
})

</script>